//
//  ViewController.m
//  dispatch_group
//
//  Created by 梁森 on 17/4/7.
//  Copyright © 2017年 梁森. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    NSString * _str1;
    NSString * _str2;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    self.view.backgroundColor = [UIColor greenColor];
    
    dispatch_queue_t myqueue = dispatch_queue_create("myqueue.queue",DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(myqueue, ^{
        NSLog(@"任务1");
    });
    
    dispatch_async(myqueue, ^{
        NSLog(@"任务2");
    });
    
    dispatch_barrier_async(myqueue, ^{
        NSLog(@"===============任务3===============");
    });
    
    
    dispatch_async(myqueue, ^{
        NSLog(@"任务4");
    });
    dispatch_async(myqueue, ^{
        NSLog(@"任务5");
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"开始...");
    // 全局变量group
    dispatch_group_t group = dispatch_group_create();
    // 并行队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 进入组（进入组和离开组必须成对出现, 否则会造成死锁）
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        // 执行异步任务1
        [NSThread sleepForTimeInterval:2];
        for (int i = 0; i < 3; i ++) {
            NSLog(@"1---%@",[NSThread currentThread ]);    // 子线程
        }
        _str1 = @"str1";
        dispatch_group_leave(group);
    });
    
    // 进入组
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        // 执行异步任务2
        [NSThread sleepForTimeInterval:2];
        for (int i = 3; i < 6; i ++) {
            NSLog(@"2---%@",[NSThread currentThread ]);
        }
        _str2 = @"str2";
        dispatch_group_leave(group);
        
    });
    // wait
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"%@", [NSThread currentThread]);
        _str1 = @"str..";
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", _str1);
            NSLog(@"%@", _str2);
            NSLog(@"%@", [NSThread currentThread]); // 主线程
        });
    });
    
    return;
    dispatch_group_notify(group, queue, ^{  // 监听组里所有线程完成的情况
       
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
           NSLog(@"%@", [NSThread currentThread]);
            _str1 = @"str..";
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@", _str1);
                NSLog(@"%@", _str2);
                NSLog(@"%@", [NSThread currentThread]); // 主线程
                NSLog(@"完成...");
            });
            
        });
        
    });
    
    
}



@end
